package com.sinodoggo.shitcloud.controller;


import com.sinodoggo.shitcloud.commons.Result;
import com.sinodoggo.shitcloud.entity.Comment;
import com.sinodoggo.shitcloud.service.ICommentService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sinodoggo
 * @since 2022-11-26
 */
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Resource
    private ICommentService commentService;

    /**
     * 理想状态下是返回树型结构
     * @param articleId 关联的博文ID
     * @return 结果集——返回一级评论
     */
    @GetMapping("/{articleId}")
    public Result getCorrespondingComments(@PathVariable Integer articleId) {
        // 获取所有评论和回复
        List<Comment> comments = commentService.getCorrespondingComments(articleId);
        // 过滤出所有一级评论(不是回复)
        final List<Comment> parentComments = comments.stream().filter(comment -> comment.getOriginId() == null).collect(Collectors.toList());
        for (Comment parentComment : parentComments) {
            // 获取一级评论下对应的所有回复，并进行再组织
            final List<Comment> subComments = comments.stream().filter(comment -> parentComment.getId().equals(comment.getOriginId())).collect(Collectors.toList());
            // 找到所有回复的父级
            for (Comment subComment : subComments) {
                comments.stream().filter(comment -> subComment.getPid().equals(comment.getId())).findFirst().ifPresent(item -> {
                    subComment.setPUserId(item.getUserId());
                    subComment.setPNickName(item.getNickName());
                });
            }
            parentComment.setChildren(subComments);
        }
        return Result.success(parentComments);
//        return Result.success(comments);
    }

    @DeleteMapping("/{id}")
    public Result deleteArticleById(@PathVariable Integer id) {
        commentService.removeById(id);
        return Result.success();
    }

    @PostMapping
    public Result saveOrUpdateComment(@RequestBody Comment comment) {
        if (null != comment.getPid()) {
            final Integer pid = comment.getPid();
            final Comment pComment = commentService.getById(pid);
            comment.setPUserId(pComment.getUserId());
            comment.setPNickName(pComment.getNickName());
        }
        commentService.saveOrUpdate(comment);
        return Result.success();
    }
}

